package com.jay.media.kit

import android.util.Log

/**
 * Create by xuzhou4
 * Date 2021/11/12
 */
object LogHelper {

    private const val LOG_PREFIX = "JAY_"
    private const val LOG_PREFIX_LENGTH: Int = LOG_PREFIX.length
    private const val MAX_LOG_LENGTH: Int = 23
    private const val DEBUG = true

    fun <T> makeLogTag(clazz: Class<T>): String {
        return makeLogTag(clazz.simpleName)
    }

    private fun makeLogTag(str: String): String {
        if (str.length > (MAX_LOG_LENGTH - LOG_PREFIX_LENGTH)) {
            return LOG_PREFIX + str.substring(0, MAX_LOG_LENGTH - LOG_PREFIX_LENGTH + 1)
        }
        return LOG_PREFIX + str
    }

    fun d(tag: String, vararg messages: String) {
        if (DEBUG) {
            log(tag, Log.DEBUG, null, messages.toList())
        }
    }

    fun e(tag: String, vararg messages: String) {
        log(tag, Log.ERROR, null, messages.toList())
    }

    fun log(tag: String, level: Int, t: Throwable?, messages: List<String>?) {
        val message = if (t == null && messages != null && messages.size == 1) {
            messages[0]
        } else {
            val stringBuilder = StringBuilder()
            messages?.also {
                for (s in it) {
                    stringBuilder.append(s)
                }
            }

            t?.also {
                stringBuilder.append("\n").append(Log.getStackTraceString(t))
            }
            stringBuilder.toString()
        }
        Log.println(level, tag, message)
    }


}